package com.example.teachdemo05;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;

public class MediaPlayerActivity extends AppCompatActivity {

    MediaPlayer mediaPlayer;
    boolean isReady = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media_player);
        mediaPlayer = MediaPlayer.create(this, Uri.parse("android.resource://com.example.teachdemo05/" + R.raw.abc));//设置播放资源
        //mediaPlayer = MediaPlayer.create(this,R.raw.abc);//设置播放资源
        if(mediaPlayer == null) return;

        try {
            mediaPlayer.stop();
            mediaPlayer.prepare();//准备播放
            isReady = true;

        }catch (Exception e){
            isReady = false;
        }

        if(isReady){
            if(!mediaPlayer.isPlaying()){
                Log.v("msg","isReady");
                mediaPlayer.start();//开始播放
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mediaPlayer != null && mediaPlayer.isPlaying()){
            mediaPlayer.stop();//停止播放
            mediaPlayer.release();//释放资源
        }
    }
}
